package vip.wangwenhao.sso.config.security.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import vip.wangwenhao.common.constants.CommonConstants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@Slf4j
@Component
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException {
        log.info("login error", exception);
        String message;
        if (exception instanceof BadCredentialsException) {
            message = "密码错误";
        } else if (exception instanceof UsernameNotFoundException) {
            message = "用户名不存在";
        } else if (exception instanceof CredentialsExpiredException) {
            message = "密码已过期，请先修改密码";
        } else if (exception instanceof LockedException) {
            message = "用户已暂时封号";
        } else if (exception instanceof DisabledException) {
            message = "用户已加入黑名单";
        } else {
            message = "服务器繁忙，请重试";
        }

        redirectStrategy.sendRedirect(request, response, "/login?error=" + URLEncoder.encode(message, CommonConstants.DEFAULT_CHARSET.name()));
    }
}